﻿using Common.Extension;
using System.Text.RegularExpressions;

namespace DesignModeConsole.行为型.解释器模式.自定义1;

/// <summary>
/// 告警表达式
/// </summary>
public interface IAlertRuleExpression3
{
    /// <summary>
    /// 解析
    /// </summary>
    /// <param name="tableName">表名</param>
    /// <param name="columnName">列名</param>
    /// <returns></returns>
    bool Interpret(string tableName, string columnName);
}

/// <summary>
/// 正则表达式
/// </summary>
public class RegexExpression3 : IAlertRuleExpression3
{
    private readonly string _key;
    private readonly string _regexStr;


    public RegexExpression3(string key, string regexStr)
    {
        if (key.IsNullOrEmpty() || regexStr.IsNullOrEmpty())
            throw new ArgumentNullException(key, "表达式不能为空");

        _key = key.Trim();
        _regexStr = regexStr.Trim().Trim('\'');
    }

    public RegexExpression3(string expression)
    {
        if (expression.IsNullOrEmpty())
            throw new ArgumentNullException(expression, "表达式不能为空");

        var elements = expression.Trim().Split(" ");
        if (elements.Length != 3 || !elements[1].Trim().Equals("~"))
        {
            throw new ArgumentException("无效的表达式");
        }

        _key = elements[0].Trim();
        _regexStr = elements[2].Trim().Trim('\'');
    }

    public bool Interpret(string tableName, string columnName)
    {
        return Regex.IsMatch(_key == "table_name" ? tableName : columnName, _regexStr);
    }
}